import React, { useEffect, useRef, useState } from 'react'
import { ProTable } from '@ant-design/pro-components'
import { Button, Popconfirm, Modal, Form, Input, Radio, InputNumber, Image, Switch, App } from 'antd'
import { useModel } from '@umijs/max'
import { EditTwoTone, PlusOutlined } from '@ant-design/icons'
import dayjs from 'dayjs'
import './ProductCategory.less'
import Upload from '@/components/Upload'

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 }
}

export default () => {
  const {
    GetCategoryList,
    CreateCategory,
    UpdateCategory,
    DeleteCategory,
    ChangeCategoryStatus,
    SetSort,
    GetShowPlts,
    GetPltCateCount
  } = useModel('ProductCategory')

  const { message, modal } = App.useApp()

  const tableRef = useRef()
  const [currentPage, setCurrentPage] = useState(1) //  当前页码
  const [pageSize, setPageSize] = useState(10) //  每页数量

  const [addAndEditModalVisible, setAddAndEditModalVisible] = useState(false) // 新增/编辑分类弹窗
  const [addAndEditModalType, setAddAndEditModalType] = useState('add') // 新增/编辑分类弹窗类型
  const [modalTitle, setModalTitle] = useState('新建一级分类') // 新增/编辑分类弹窗标题

  const [formRef] = Form.useForm()
  const [editRow, setEditRow] = useState({}) // 弹窗分类临时存放数据

  const [sortNum, setSortNum] = useState(null) //  商品排序值
  const [sortingKey, setSortingKey] = useState(null) //  商品排序

  const [picture, setPicture] = useState('') // 上传图片

  // tab 选项卡
  const [tabActiveKey, setTabActiveKey] = useState(null)
  const [tabStatusCount, setTabStatusCount] = useState({})
  const [tabList, setTabList] = useState([])

  // 获取列表数量
  const handleGetTabCount = async () => {
    const res = await GetPltCateCount()
    setTabStatusCount(res)
  }

  useEffect(() => {
    handleGetTabList()
  }, [])

  // 获取tab列表
  const handleGetTabList = async () => {
    const res = await GetShowPlts()
    let arr = []
    // eslint-disable-next-line guard-for-in
    for (const resKey in res) {
      arr.push({
        key: Number(resKey),
        tab: res[resKey],
        num: '0'
      })

      // 默认选中第一个
      if (arr.length === 1) {
        setTabActiveKey(resKey + '')
      } else {
        setTabActiveKey('1')
      }
    }

    setTabList(arr)
  }

  // 格式化 tab
  const formatTabs = () => {
    if (tabList && tabList.length > 0) {
      for (const key in tabStatusCount) {
        let index = tabList.findIndex(item => Number(item.key) === Number(key))
        if (index !== -1) {
          tabList[index].num = tabStatusCount[key]
        }
      }

      let arr = []
      tabList.forEach(item => {
        arr.push({
          key: item.key,
          tab: (
            <div>
              <span>{item.tab}</span>
              <span className={Number(item.key) === Number(tabActiveKey) ? 'tab_badge_active' : 'tab_badge'}>
                {item.num}
              </span>
            </div>
          )
        })
      })
      return arr
    }
  }

  // 处理 tab 切换
  const handleTabActive = key => {
    setTabActiveKey(key)
    setCurrentPage(1)
    tableRef.current.reload()
  }

  // 处理图片上传
  const normFile = e => {
    if (e && e.length) {
      const { value, key } = e[0]
      if (value) {
        return value
      } else {
        return ''
      }
    } else {
      return ''
    }
  }

  // 删除
  const handleDelete = async id => {
    const res = await DeleteCategory({ id })
    if (res) {
      message.success('操作成功')
      tableRef.current.reload()
    }
  }

  // 新增/编辑分类
  const handleAddAndEdit = async (type, row) => {
    formRef.setFieldsValue({
      cate_status: 1
    })
    setAddAndEditModalType(type)
    setAddAndEditModalVisible(true)

    let obj = {
      ...row
    }

    switch (type) {
      case 'add':
        obj.cate_pid = 0
        setModalTitle('新建一级分类')
        break
      case 'add_sub':
        obj.cate_pid = row.id
        setModalTitle('新建子分类')
        break
      case 'edit':
        setModalTitle('编辑分类')
        formRef.setFieldsValue({
          ...row
        })
        setPicture(row.cate_pic_url)
        break
    }

    setEditRow(obj)
  }

  // 新增/编辑增值服务弹窗确认
  const handleAddAndEditOk = async () => {
    let type = addAndEditModalType
    let { cate_name } = formRef.getFieldsValue() // 输入框的内容

    // 判断是新增一级还是二级
    let remark = ''
    if (editRow.cate_pid === 0) {
      remark = cate_name
    } else {
      remark = `${editRow.cate_name}/${cate_name}`
    }
    console.log(editRow)

    let params = {
      ...editRow,
      ...formRef.getFieldsValue(),
      remark,
      plt: tabActiveKey
    }

    let res

    if (type === 'add' || type === 'add_sub') {
      res = await CreateCategory(params)
    } else if (type === 'edit') {
      res = await UpdateCategory(params)
    }

    if (res) {
      message.success('操作成功')
      handleAddAndEditCancel()
      tableRef.current.reload()
    }
  }

  // 关闭弹窗
  const handleAddAndEditCancel = () => {
    setAddAndEditModalVisible(false)
    formRef.resetFields()
  }

  // 状态开关
  const changeStatusSwitch = ({ id, cate_status }) => {
    const config = {
      title: '提示',
      content: '禁用后用户小程序将不显示该分类，是否确定禁用?',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        await changeStatusSwitchFn(id)
      }
    }
    if (Number(cate_status) === 1) {
      modal.confirm(config)
    } else {
      changeStatusSwitchFn(id)
    }
  }

  // 状态开关触发请求
  const changeStatusSwitchFn = async id => {
    const res = await ChangeCategoryStatus({ id })
    if (res) {
      message.success('操作成功')
      tableRef.current.reload()
    }
  }

  //  确认排序
  const onSort = async (value, id) => {
    const params = {
      id,
      sort: Math.floor(value)
    }
    const res = await SetSort(params)
    if (res) {
      setSortingKey(null)
      tableRef.current.reload()
    }
  }

  //  排序键盘事件
  const sortKeyDown = (e, id) => {
    const {
      code,
      target: { value }
    } = e
    if (code === 'Escape') {
      setSortingKey(null)
    } else if (code === 'Enter') {
      onSort(value, id)
    }
  }

  //  排序状态切换
  const onSorting = (row, value) => {
    setSortNum(value)
    setSortingKey(row.id)
  }

  const columns = [
    {
      title: '分类名称',
      dataIndex: 'cate_name',
      width: 120,
      align: 'center',
      hideInSearch: true,
      render: (text, record) => {
        {
          return record.cate_pid === 0 ? (
            <div style={{ fontWeight: '500', color: '#1677ff' }}>{text}</div>
          ) : (
            <div>{text}</div>
          )
        }
      }
    },
    {
      title: 'ID',
      dataIndex: 'id',
      width: 100,
      align: 'center',
      hideInSearch: true
    },
    {
      title: '所属行业',
      dataIndex: 'industry',
      width: 100,
      align: 'center',
      hideInSearch: true
    },
    {
      title: '分类封面图',
      dataIndex: 'cate_pic_url',
      width: 80,
      align: 'center',
      hideInSearch: true,
      render: (text, record) => {
        let { cate_pid } = record
        return cate_pid !== 0 ? (
          <Image
            src={record.cate_pic_url}
            style={{
              width: '50px',
              height: '50px',
              objectFit: 'contain'
            }}
          />
        ) : (
          '--'
        )
      }
    },
    {
      title: '状态',
      dataIndex: 'cate_status',
      width: 80,
      align: 'center',
      valueType: 'select',
      valueEnum: {
        1: { text: '启用', status: 'Success' },
        2: { text: '禁用', status: 'Error' }
      },
      render: (text, record) => {
        return (
          <Switch
            checked={record.cate_status === 1}
            checkedChildren='开启'
            unCheckedChildren='关闭'
            disabled={record.cate_pid !== 0 && !record.parent_disabled}
            onChange={() => changeStatusSwitch(record)}
          />
        )
      }
    },
    {
      title: '排序',
      dataIndex: 'sort',
      width: 110,
      hideInSearch: true,
      align: 'center',
      render: (item, record, index) =>
        record.id === sortingKey ? (
          <InputNumber
            style={{ background: '#fff' }}
            onKeyDown={e => sortKeyDown(e, record.id)}
            precision={0}
            bordered={false}
            defaultValue={sortNum}
            autoFocus
            onBlur={e => onSort(e.target.value, record.id)}
          />
        ) : (
          <div style={{ cursor: 'pointer' }} onClick={e => onSorting(record, item)}>
            {item} <EditTwoTone />
          </div>
        )
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      width: 150,
      align: 'center',
      valueType: 'dateTimeRange',
      render: (text, record) => <div>{record.created_at}</div>,
      search: {
        transform: value => {
          return {
            start_time: dayjs(value[0]['$d']).format('YYYY-MM-DD HH:mm:ss'),
            end_time: dayjs(value[1]['$d']).format('YYYY-MM-DD HH:mm:ss')
          }
        }
      }
    },
    {
      title: '操作',
      key: 'option',
      width: 150,
      valueType: 'option',
      fixed: 'right',
      align: 'right',
      render: (_, row, index, action) => {
        return (
          <>
            {
              <>
                {row.cate_pid === 0 && (
                  <Button type='link' key='add_sub' onClick={() => handleAddAndEdit('add_sub', row)}>
                    新建子分类
                  </Button>
                )}
                <Button type='link' key='edit' onClick={() => handleAddAndEdit('edit', row)}>
                  编辑
                </Button>

                <Popconfirm
                  key='delete'
                  title='是否确认删除该分类？'
                  onConfirm={() => handleDelete(row.id)}
                  okText='确认'
                  cancelText='取消'
                >
                  <Button type='link' danger>
                    删除
                  </Button>
                </Popconfirm>
              </>
            }
          </>
        )
      }
    }
  ]

  return (
    <>
      {tabActiveKey ? (
        <ProTable
          actionRef={tableRef}
          request={async params => {
            const param = {
              page: params.current,
              page_size: params.pageSize,
              plt: tabActiveKey,
              cate_status: params.cate_status,
              start_time: params.start_time,
              end_time: params.end_time
            }

            setCurrentPage(params.current)
            setPageSize(params.pageSize)

            const res = await GetCategoryList(param)

            let arr = res.data.map(item => {
              if (item.children && item.children.length === 0) {
                delete item.children
              }

              let obj = {
                ...item,
                sortVisible: false
              }

              if (item.children) {
                obj.children = item.children.map(child => {
                  return {
                    ...child,
                    parent_disabled: item.parent_disabled,
                    sortVisible: false
                  }
                })
              }

              return obj
            })

            await handleGetTabCount()
            return {
              data: arr,
              success: true,
              total: res.total
            }
          }}
          pagination={{
            pageSize: pageSize,
            current: currentPage
          }}
          rowKey='id'
          scroll={{ x: 'max-content' }}
          columns={columns}
          headerTitle={
            <Button
              icon={<PlusOutlined />}
              key={Math.random().toString()}
              type='primary'
              onClick={() => handleAddAndEdit('add')}
            >
              新建一级分类
            </Button>
          }
          search={{
            defaultCollapsed: false,
            labelWidth: 80,
            span: 8
          }}
          toolbar={{
            multipleLine: true,
            tabs: {
              onChange: key => handleTabActive(key),
              activeKey: tabActiveKey,
              items: formatTabs()
            }
          }}
        />
      ) : null}

      {/* 新增/编辑弹窗 */}
      <Modal
        title={modalTitle}
        mask
        open={addAndEditModalVisible}
        onCancel={() => handleAddAndEditCancel()}
        bodyStyle={{ padding: '20px 0' }}
        width={640}
        onOk={() => formRef.submit()}
        destroyOnClose
      >
        <Form form={formRef} onFinish={handleAddAndEditOk} name='form_modal' {...formItemLayout}>
          <Form.Item name='cate_name' label='名称 : ' rules={[{ required: true, message: '请输入名称' }]}>
            <Input placeholder='请输入' allowClear />
          </Form.Item>
          <Form.Item name='sort' label='排序 : ' rules={[{ required: true, message: '请输入排序' }]}>
            <InputNumber placeholder='请输入' style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name='cate_status' label='状态 : ' rules={[{ required: true, message: '请选择状态' }]}>
            <Radio.Group>
              <Radio value={1}>启动</Radio>
              <Radio value={2}>禁用</Radio>
            </Radio.Group>
          </Form.Item>
          {editRow.cate_pid !== 0 && (
            <Form.Item
              name='cate_pic_url'
              label='封面：'
              rules={[{ required: true, message: '请上传封面' }]}
              valuePropName='cate_pic_url_'
              getValueFromEvent={normFile}
            >
              <Upload
                formProps={{
                  name: 'file',
                  listType: 'picture-card'
                }}
                key={'picture'}
                maxCount={1}
                value={picture}
              ></Upload>
            </Form.Item>
          )}
        </Form>
      </Modal>
    </>
  )
}
